package com.learn.window;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

/**
 * @create: 2023-04-20 10:00
 * @author: Mr.Du
 * --------------
 * @notes: 演示窗口对象的apply方法
 **/
public class ApplyWindowFunctionDemo {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStreamSource<String> source = env.socketTextStream("node1", 9999);
        SingleOutputStreamOperator<Tuple2<String, Integer>> streamOperator = source
                .flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
                    @Override
                    public void flatMap(String line, Collector<Tuple2<String, Integer>> out) throws Exception {
                        String[] words = line.split(" ");
                        for (String word : words
                        ) {
                            out.collect(Tuple2.of(word, 1));
                        }
                    }
                });

        WindowedStream<Tuple2<String, Integer>, Tuple, TimeWindow> windowedStream = streamOperator
                .keyBy(0)
                .window(TumblingProcessingTimeWindows.of(Time.seconds(10)));

        windowedStream
                .apply(new WindowFunction<Tuple2<String, Integer>, Tuple2<String,Integer>, Tuple, TimeWindow>() {
                    @Override
                    public void apply(Tuple tuple, TimeWindow timeWindow, Iterable<Tuple2<String, Integer>> iterable, Collector<Tuple2<String, Integer>> out) throws Exception {
                        int sum = 0;
                        String key = null;

                        for (Tuple2<String,Integer> wordAndOne:iterable
                             ) {
                            sum += wordAndOne.f1;
                            key = wordAndOne.f0;
                        }
                        out.collect(Tuple2.of(key,sum));
                    }
                }).print();

        env.execute();
    }
}
